package db

import (
	"database/sql"
	myDB "db/mysql"
	"fmt"
)

func OnFileUploadFinished(fileHash string, fileName string,
	fileSize int64, fileAddr string) bool {
	statement, err := myDB.GetDBConn().Prepare(
		"insert ignore into  tbl_file(file_sha1, file_name, file_size, file_addr, status)" +
			"    value (?, ?, ?, ?, 1)")
	if err != nil {
		fmt.Printf("Failed to prepare statement, err:" + err.Error())
		return false
	}
	defer statement.Close()
	result, err := statement.Exec(fileHash, fileName, fileSize, fileAddr)
	if affected, err := result.RowsAffected(); err == nil {
		if affected <= 0 {
			fmt.Printf("File with hash:%s has been uploaded before", fileHash)
		}
		return true
	}
	return false
}

type TableFile struct {
	FileHash string
	FileName sql.NullString
	FileSize sql.NullInt64
	FileAddr sql.NullString
}

func GetFiledMeta(fileHash string) *TableFile {
	statement, err := myDB.GetDBConn().Prepare("select file_sha1, file_name, file_size, file_addr " +
		"from tbl_file " +
		"where file_sha1 = ? " +
		" and status = 1 limit 1")
	if err != nil {
		fmt.Printf("Failed to prepare statement, err:" + err.Error())
		return nil
	}
	defer statement.Close()
	tableFile := TableFile{}
	err = statement.QueryRow(fileHash).Scan(&tableFile.FileHash, &tableFile.FileName, &tableFile.FileSize, &tableFile.FileAddr)
	if err != nil {
		fmt.Printf(err.Error())
	}
	return &tableFile
}

// UpdateFileLocation : 更新文件的存储地址(如文件被转移了)
func UpdateFileLocation(filehash string, fileaddr string) bool {
	stmt, err := myDB.GetDBConn().Prepare(
		"update tbl_file set`file_addr`=? where  `file_sha1`=? limit 1")
	if err != nil {
		fmt.Println("预编译sql失败, err:" + err.Error())
		return false
	}
	defer stmt.Close()

	ret, err := stmt.Exec(fileaddr, filehash)
	if err != nil {
		fmt.Println(err.Error())
		return false
	}
	if rf, err := ret.RowsAffected(); nil == err {
		if rf <= 0 {
			fmt.Printf("更新文件location失败, filehash:%s", filehash)
		}
		return true
	}
	return false
}
